<template>
  <view>
    <u-upload
        v-if="!curValue"
        :fileList="list"
        @afterRead="afterRead"
        :name="name"
        :maxCount="1"
    ></u-upload>
    <view v-else class="relative">
      <u-image @click="handlePreview(prefix+curValue)" :show-loading="true" :src="prefix+curValue" width="80px" height="80px"></u-image>
      <view class="absolute top-0 right-0">
        <u-icon name="trash" @click="handleRemove"></u-icon>
      </view>
    </view>
  </view>
</template>
<script setup lang="ts">
import {computed, ref} from "vue";
import {uploadFile, imagePathPrefix} from '/settings'
import api from "@/api";

const url = uploadFile.url
const name = uploadFile.name
const prefix = imagePathPrefix

const props = defineProps({
  value: {
    type: [String, Number],
    default: ''
  }
})
const list = ref([])

const emits = defineEmits(['update:value'])
const curValue = computed({
  get() {
    return props.value
  },
  set(val) {
    emits('update:value', val)
  }
})

const afterRead = (event: any) => {
  let file = event.file
  uni.uploadFile({
    url: url,
    filePath: file.url,
    name: name,
    success: (res: any) => {
      res = JSON.parse(res.data)
      console.log(res.data.path)
      console.log(res.code)
      if (res.code === 0) {
        curValue.value = res.data.path
        uni.showToast({
          icon: 'success',
          title: '上传成功'
        })
      }
    }
  })
}

const handleRemove=()=>{
  api.file.removeByPath({
    path:curValue.value
  }).then((res:any)=>{
    if (res.data.code === 0) {
      curValue.value=''
      uni.showToast({
        icon: 'success',
        title: '删除成功'
      })
    }
  }).finally(()=>{
    curValue.value=''
  })
}

const handlePreview=(url:string)=>{
  uni.previewImage({
    urls: [url],
    longPressActions: {
      itemList: ['发送给朋友', '保存图片', '收藏'],
      success: function(data) {
        console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
      },
      fail: function(err) {
        console.log(err.errMsg);
      }
    }
  });
}

</script>

<style scoped>

</style>